package com.store.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.store.dto.OrderCreateRequest;
import com.store.entity.*;
import com.store.mapper.*;
import com.store.vo.CartVO;
import com.store.vo.OrderItemVO;
import com.store.vo.OrderVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单服务类
 */
@Service
@RequiredArgsConstructor
public class OrderService {
    
    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final CartMapper cartMapper;
    private final ProductMapper productMapper;
    private final UserMapper userMapper;
    
    /**
     * 从购物车创建订单
     */
    @Transactional(rollbackFor = Exception.class)
    public Long createOrder(Long userId, OrderCreateRequest request) {
        // 1. 验证购物车记录
        List<CartVO> cartList = new ArrayList<>();
        for (Long cartId : request.getCartIds()) {
            Cart cart = cartMapper.selectById(cartId);
            if (cart == null) {
                throw new RuntimeException("购物车记录不存在：" + cartId);
            }
            if (!cart.getUserId().equals(userId)) {
                throw new RuntimeException("无权操作此购物车记录");
            }
            
            // 获取购物车详情
            CartVO cartVO = cartMapper.selectCartListByUserId(userId).stream()
                    .filter(c -> c.getId().equals(cartId))
                    .findFirst()
                    .orElseThrow(() -> new RuntimeException("购物车商品不存在"));
            
            cartList.add(cartVO);
        }
        
        // 2. 验证商品状态和库存
        for (CartVO cartVO : cartList) {
            if (cartVO.getStatus() == null || cartVO.getStatus() != 1) {
                throw new RuntimeException("商品已下架：" + cartVO.getProductName());
            }
            if (cartVO.getStock() == null || cartVO.getStock() < cartVO.getQuantity()) {
                throw new RuntimeException("商品库存不足：" + cartVO.getProductName());
            }
        }
        
        // 3. 计算订单总金额
        BigDecimal totalAmount = cartList.stream()
                .map(CartVO::getSubtotal)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        // 4. 生成订单号
        String orderNo = generateOrderNo();
        
        // 5. 创建订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setTotalAmount(totalAmount);
        order.setPaymentMethod(request.getPaymentMethod());
        order.setStatus("paid"); // 默认已支付（简化流程）
        order.setAddress(request.getAddress());
        order.setPhone(request.getPhone());
        order.setRemark(request.getRemark());
        order.setPayTime(LocalDateTime.now());
        
        orderMapper.insert(order);
        
        // 6. 创建订单明细
        for (CartVO cartVO : cartList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(cartVO.getProductId());
            orderItem.setProductName(cartVO.getProductName());
            orderItem.setProductImage(cartVO.getProductImage());
            orderItem.setPrice(cartVO.getPrice());
            orderItem.setQuantity(cartVO.getQuantity());
            orderItem.setSubtotal(cartVO.getSubtotal());
            
            orderItemMapper.insert(orderItem);
        }
        
        // 7. 扣减库存
        for (CartVO cartVO : cartList) {
            Product product = productMapper.selectById(cartVO.getProductId());
            if (product != null) {
                int newStock = product.getStock() - cartVO.getQuantity();
                if (newStock < 0) {
                    throw new RuntimeException("库存扣减失败：" + product.getName());
                }
                product.setStock(newStock);
                // 增加销量
                product.setSales((product.getSales() == null ? 0 : product.getSales()) + cartVO.getQuantity());
                productMapper.updateById(product);
            }
        }
        
        // 8. 删除购物车记录
        cartMapper.deleteBatchIds(request.getCartIds());
        
        return order.getId();
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        // 格式：yyyyMMddHHmmss + 6位随机数
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.format("%06d", (int)(Math.random() * 1000000));
        return timestamp + random;
    }
    
    /**
     * 查询用户订单列表
     */
    public IPage<OrderVO> getOrderList(Long userId, int page, int pageSize) {
        Page<Order> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserId, userId);
        queryWrapper.orderByDesc(Order::getCreateTime);
        
        IPage<Order> orderPage = orderMapper.selectPage(pageParam, queryWrapper);
        
        // 转换为VO
        IPage<OrderVO> voPage = orderPage.convert(this::convertToVO);
        
        return voPage;
    }
    
    /**
     * 获取订单详情
     */
    public OrderVO getOrderDetail(Long userId, Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权查看此订单");
        }
        
        return convertToVO(order);
    }
    
    /**
     * 取消订单
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long userId, Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此订单");
        }
        if (!"unpaid".equals(order.getStatus()) && !"paid".equals(order.getStatus())) {
            throw new RuntimeException("订单状态不允许取消");
        }
        
        // 更新订单状态
        order.setStatus("cancelled");
        order.setCancelTime(LocalDateTime.now());
        orderMapper.updateById(order);
        
        // 恢复库存
        List<OrderItem> items = getOrderItems(orderId);
        for (OrderItem item : items) {
            Product product = productMapper.selectById(item.getProductId());
            if (product != null) {
                product.setStock(product.getStock() + item.getQuantity());
                product.setSales(product.getSales() - item.getQuantity());
                productMapper.updateById(product);
            }
        }
    }
    
    /**
     * 获取订单明细
     */
    private List<OrderItem> getOrderItems(Long orderId) {
        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getOrderId, orderId);
        return orderItemMapper.selectList(queryWrapper);
    }
    
    /**
     * 管理员查询所有订单（分页+筛选）
     */
    public IPage<OrderVO> getAdminOrderList(int page, int pageSize, String orderNo, 
                                             String status, String startDate, String endDate) {
        Page<Order> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        
        // 订单号筛选
        if (orderNo != null && !orderNo.trim().isEmpty()) {
            queryWrapper.like(Order::getOrderNo, orderNo.trim());
        }
        
        // 状态筛选
        if (status != null && !status.trim().isEmpty()) {
            queryWrapper.eq(Order::getStatus, status);
        }
        
        // 日期范围筛选
        if (startDate != null && !startDate.trim().isEmpty()) {
            queryWrapper.ge(Order::getCreateTime, startDate + " 00:00:00");
        }
        if (endDate != null && !endDate.trim().isEmpty()) {
            queryWrapper.le(Order::getCreateTime, endDate + " 23:59:59");
        }
        
        queryWrapper.orderByDesc(Order::getCreateTime);
        
        IPage<Order> orderPage = orderMapper.selectPage(pageParam, queryWrapper);
        
        // 转换为VO
        IPage<OrderVO> voPage = orderPage.convert(this::convertToVO);
        
        return voPage;
    }
    
    /**
     * 管理员查看订单详情（无权限限制）
     */
    public OrderVO getAdminOrderDetail(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        return convertToVO(order);
    }
    
    /**
     * 发货
     */
    @Transactional(rollbackFor = Exception.class)
    public void shipOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!"paid".equals(order.getStatus())) {
            throw new RuntimeException("只有已支付的订单才能发货");
        }
        
        order.setStatus("shipped");
        order.setShipTime(LocalDateTime.now());
        orderMapper.updateById(order);
    }
    
    /**
     * 确认收货
     */
    @Transactional(rollbackFor = Exception.class)
    public void receiveOrder(Long userId, Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此订单");
        }
        if (!"shipped".equals(order.getStatus())) {
            throw new RuntimeException("只有已发货的订单才能确认收货");
        }
        
        order.setStatus("completed");
        order.setCompleteTime(LocalDateTime.now());
        orderMapper.updateById(order);
    }
    
    /**
     * 完成订单（管理员/员工直接完成）
     */
    @Transactional(rollbackFor = Exception.class)
    public void completeOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!"paid".equals(order.getStatus()) && !"shipped".equals(order.getStatus())) {
            throw new RuntimeException("只有已支付或已发货的订单才能完成");
        }
        
        order.setStatus("completed");
        order.setCompleteTime(LocalDateTime.now());
        orderMapper.updateById(order);
    }
    
    /**
     * 转换为VO
     */
    private OrderVO convertToVO(Order order) {
        OrderVO vo = new OrderVO();
        vo.setId(order.getId());
        vo.setOrderNo(order.getOrderNo());
        vo.setUserId(order.getUserId());
        vo.setEmployeeId(order.getEmployeeId());
        vo.setTotalAmount(order.getTotalAmount());
        vo.setPaymentMethod(order.getPaymentMethod());
        vo.setStatus(order.getStatus());
        vo.setAddress(order.getAddress());
        vo.setPhone(order.getPhone());
        vo.setRemark(order.getRemark());
        vo.setPayTime(order.getPayTime());
        vo.setShipTime(order.getShipTime());
        vo.setCompleteTime(order.getCompleteTime());
        vo.setCancelTime(order.getCancelTime());
        vo.setCreateTime(order.getCreateTime());
        vo.setUpdateTime(order.getUpdateTime());
        
        // 查询用户信息
        User user = userMapper.selectById(order.getUserId());
        if (user != null) {
            vo.setUsername(user.getUsername());
        }
        
        // 查询订单明细
        List<OrderItemVO> items = orderItemMapper.selectByOrderId(order.getId());
        vo.setItems(items);
        
        return vo;
    }
}


